<template>
  <div>
    <el-card>
      <el-descriptions class="margin-top" title="个人信息" :column="2" border>
        <template slot="extra">
          <el-button type="primary" plain icon="el-icon-edit" circle @click="updateReader()" size="small"></el-button>
        </template>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-picture-outline"></i>头像</template>
          <img class="img" :src="readerForm.icon"/>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-reading"></i>
            读书卡号
          </template>
          {{ readerForm.readernumber }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-s-custom"></i>
            昵称
          </template>
          {{ readerForm.realname }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            账号
          </template>
          {{ readerForm.username }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-male"></i>
            <i class="el-icon-female"></i>
            性别
          </template>
          {{ readerForm.sex }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-message"></i>
            邮箱
          </template>
          {{ readerForm.email }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-mobile-phone"></i>
            手机号码
          </template>
          {{ readerForm.tel }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-location-outline"></i>
            地区
          </template>
          {{ readerForm.address }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-star-off"></i>
            生日
          </template>
          {{ readerForm.birthday }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-date"></i>
            注册日期
          </template>
          {{ readerForm.registerdate }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <el-dialog
        title="修改个人信息"
        :visible.sync="dialogVisible"
        width="60%"
        :before-close="handleClose"
        append-to-body>

      <el-form :model="readerForm" :rules="rules" ref="readerForm" label-width="120px">
        <div class="updateinfo">
          <div class="left">
            <el-form-item label="头像" prop="icon">
              <el-upload
                  class="avatar-uploader"
                  action=""
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="changePicture"
                  :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="昵称" prop="realname">
              <el-input v-model="readerForm.realname"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="tel">
              <el-input v-model="readerForm.tel"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="readerForm.sex">
                <el-radio label="男"></el-radio>
                <el-radio label="女"></el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div class="right">
            <el-form-item label="读书卡号" prop="readernumber">
              <el-input v-model="readerForm.readernumber" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="账号" prop="username">
              <el-input v-model="readerForm.username" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="生日" prop="birthday">
              <el-date-picker
                  v-model="readerForm.birthday"
                  type="date"
                  placeholder="选择日期"
              style="width: 100%">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="readerForm.address"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="readerForm.email"></el-input>
            </el-form-item>
          </div>
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button @click="cancelDialog">取 消</el-button>
    <el-button type="primary" @click="subForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>


</template>

<script>
import dayjs from 'dayjs';
export default {
  name: "Info",
  data(){
    var validateRealname = async (rule, value, callback) => {
      const {data:res} = await this.$axios.get("reader/checkRealname",{params:{realname:this.readerForm.realname,id:this.readerForm.id}})
      if (res.data==null){
        callback();
      }else if (value===res.data.realname && res.data.id !== this.readerForm.id){
        callback(new Error('昵称已存在'));
      }else{
        callback();
      }
    };
    return {
      formData: new FormData(),
      readerForm:{
        readernumber: '',
        username: '',
        realname: '',
        sex: '',
        tel: '',
        email: '',
        birthday:'',
        registerdate:'',
        address:'',
        icon:'',
        id:'',
      },
      imageUrl: '',
      dialogVisible: false,
      rules: {
        realname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          {validator:validateRealname, trigger: 'change'}
        ],
        tel: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
      }
    }
  },
  created() {
    this.fetchReaderData();
  },
  methods: {
    subForm() {
      this.$refs.readerForm.validate(async valid => {
        if (valid){
          this.readerForm.birthday = dayjs(this.readerForm.birthday).format('YYYY-MM-DD');
          this.readerForm.registerdate = dayjs(this.readerForm.registerdate).format('YYYY-MM-DD HH:mm:ss');
          for (let key in this.readerForm){
            this.formData.append(key, this.readerForm[key]);
          }
          const { data: res} = await this.$axios.post("reader/update", this.formData);
          if (res.data){
            this.$message.success('修改成功');
            this.dialogVisible = false;
            await this.fetchReaderData();
            this.formData = new FormData();
            this.$router.go(0)
          }
        }else {
          this.$message.error('请填写完整信息');
          return false;
        }
      });
    },
    async fetchReaderData() {
      const {data: res} = await this.$axios.get("/reader/getUserById", {params: {id: sessionStorage.getItem("id")}})
      if(res.data){
        this.readerForm = res.data
        this.imageUrl = res.data.icon
        sessionStorage.setItem("icon",res.data.icon)
        sessionStorage.setItem("realname",res.data.realname)
        sessionStorage.setItem("username",res.data.username)
        if (res.data.birthday) {
          this.readerForm.birthday = dayjs(res.data.birthday).isValid() ? dayjs(res.data.birthday).format('YYYY-MM-DD') : null;
        } else {
          this.readerForm.birthday = null;
        }
        this.readerForm.registerdate = dayjs(res.data.registerdate).format('YYYY-MM-DD HH:mm:ss');
      }
    },
    updateReader() {
      this.dialogVisible = true
    },
    changePicture(file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      if (this.imageUrl){
        this.formData.append('file', file.raw);
      }
    },
    beforeAvatarUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      return isLt5M;
    },
    cancelDialog(){
      this.dialogVisible = false;
      this.$refs.readerForm.resetFields();
      this.fetchReaderData();
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.dialogVisible = false;
            this.$refs.readerForm.clearValidate();
            this.fetchReaderData();
            done();
          })
          .catch(_ => {});
    },
  },
}
</script>

<style>
.img {
  width: 80px;
  height: 80px;
}
.updateinfo {
  height: 300px;
  overflow: auto;
}
.left {
  /* width: 330px; */
  float: left;
}
.right {
  overflow: hidden;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 110px;
  height: 110px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 110px;
  height: 110px;
  display: block;
}
</style>